﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Threading;
using System.Windows.Threading;
using System.Xml;
using System.Windows.Navigation;
using System.Xml.Linq;
using System.Diagnostics;
using Microsoft.Phone.Tasks;
using System.Windows.Interactivity;
using WP7Contrib.View.Controls.Behaviors;


namespace OpenGovernment
{
    public partial class MainPage : PhoneApplicationPage
    {
        public static OpenData data;
        public MainPage()
        {
            InitializeComponent();
            GetData.EpicFail += new GetData.EpicFailHandler(GetData_EpicFail);
            grid.Visibility = Visibility.Collapsed;
            data = new OpenData();
            data.Done += new OpenData.DoneHandler(data_Done);
        }

        void GetData_EpicFail()
        {
            Dispatcher.BeginInvoke(new Action(() =>
            {
                MessageBox.Show("Δεν μπόρεσε να πραγματοπιοιθεί σύνδεση με το διαδύκτιο. Παρακαλώ, ξαναπροσπαθήστε σε λίγο.");
            }));
        }
       
        private void Init()
        {
            grid.Visibility = Visibility.Visible;
            bar.IsIndeterminate = false;
            bar.Visibility = Visibility.Collapsed;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);            
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            PrepBoxes();
        }
        private TiltBehaviour GetTilt(double factor)
        {
            TiltBehaviour result = new TiltBehaviour();
            result.TiltFactor = factor;
            return result;
        }
        private void PrepBoxes()
        {
            GetTilt(10).Attach(logo);
            GetTilt(10).Attach(textBlock1);
            GetTilt(10).Attach(textBlock2);
            GetTilt(10).Attach(textBlock3);
            GetTilt(10).Attach(textBlock4);
            GetTilt(10).Attach(textBlock5);
            GetTilt(10).Attach(textBlock6);

            typeSelect.ItemsSource = OpenData.AddBlank(data.GetTypes());

            AutoCompleteSlideBehaviour lala = new AutoCompleteSlideBehaviour();

            lala.Attach(orgSelect);
            orgSelect.ItemsSource = data.GetOrgs();
            tagSelect.ItemsSource = data.GetTags();

            orgSelect.MinimumPrefixLength = 3;
            tagSelect.MinimumPrefixLength = 3;
            orgSelect.SelectionChanged += new SelectionChangedEventHandler(orgSelect_SelectionChanged);
            
            orgSelect.FilterMode = AutoCompleteFilterMode.Contains;
            tagSelect.FilterMode = AutoCompleteFilterMode.Contains;

            
        }
        private void GotForOrg()
        {
            unitSelect.ItemsSource = data.GetUnits();            
            signerSelect.ItemsSource = from y in data.GetSigners() select y.title + " " + y.secondname + " " + y.firstname;
            
            textBlock5.Visibility = Visibility.Visible;
            unitSelect.Visibility = Visibility.Visible;
            textBlock6.Visibility = Visibility.Visible;
            signerSelect.Visibility = Visibility.Visible;

            
        }
        void orgSelect_TextChanged(object sender, RoutedEventArgs e)
        {
            OrgSelectSelectionChanged();
        }
        void data_Done()
        {
            if (data.gets == 3)
            {
                Dispatcher.BeginInvoke(new Action(Init));
            }
            if (data.gets == 2)
            {
                Dispatcher.BeginInvoke(new Action(GotForOrg));
            }
        }
        private void Go(String messages)
        {
            NavigationService.Navigate(new Uri("/Page1.xaml?" + messages, UriKind.Relative));
        }

        private void OrgSelectSelectionChanged()
        {
            if (data.GetOrgs().Contains(orgSelect.Text))
            {
                data.GetForOrg(data.getLatin(orgSelect.Text));
            }
            else
            {
                textBlock5.Visibility = Visibility.Collapsed;
                unitSelect.Visibility = Visibility.Collapsed;
                textBlock6.Visibility = Visibility.Collapsed;
                signerSelect.Visibility = Visibility.Collapsed;
            }
        }


        void orgSelect_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            orgSelect.Text = (string)orgSelect.SelectedItem;
            OrgSelectSelectionChanged();
        }

        private void orgSelect_DropDownOpened(object sender, RoutedPropertyChangedEventArgs<bool> e)
        {
          //  DependencyObject o = VisualTreeHelper.GetChild((AutoCompleteBox)sender, 0);
          //  o = VisualTreeHelper.GetChild(o, 1);
            if (!((AutoCompleteBox)sender).Equals(orgSelect))
            {
                orgSelect.Visibility = Visibility.Collapsed;
                textBlock4.Visibility = Visibility.Collapsed;
            }
            ClearTop();
          //  ((Popup)o).
        }

        private void ClearTop()
        {
            Thickness margin = grid.Margin;
            margin.Bottom = 0;
            grid.Margin = margin;

            restore.Visibility = System.Windows.Visibility.Collapsed;
            logo.Visibility = System.Windows.Visibility.Collapsed;
            textBlock3.Visibility = Visibility.Collapsed;
            textBlock1.Visibility = Visibility.Collapsed;
            textBlock2.Visibility = Visibility.Collapsed;
            textBlock7.Visibility = Visibility.Collapsed;
            typeSelect.Visibility = Visibility.Collapsed;
            from.Visibility = Visibility.Collapsed;
            to.Visibility = Visibility.Collapsed;
            
        }

        private void orgSelect_DropDownClosed(object sender, RoutedPropertyChangedEventArgs<bool> e)
        {
            textBlock3.Visibility = Visibility.Visible;
            textBlock4.Visibility = Visibility.Visible;
            restore.Visibility = System.Windows.Visibility.Visible;
            logo.Visibility = System.Windows.Visibility.Visible;
            textBlock1.Visibility = Visibility.Visible;
            textBlock2.Visibility = Visibility.Visible;
            textBlock7.Visibility = Visibility.Visible;
            typeSelect.Visibility = Visibility.Visible;
            from.Visibility = Visibility.Visible;
            to.Visibility = Visibility.Visible;
            orgSelect.Visibility = Visibility.Visible;
            Thickness margin = grid.Margin;
            margin.Bottom = 200;
            grid.Margin = margin;

        }

        private string DigitCorrect(int number)
        {
            if (number < 10)
            {
                return "0" + number;
            }
            else
            {
                return "" + number;
            }
        }
        private string GetDate(DateTime date)
        {
            return DigitCorrect(date.Day) + "-" + DigitCorrect(date.Month) + "-" + date.Year;
        }
        private DateTime ToDateTime(DateTime? item)
        {
            if (item != null)
            {
                return item.Value;
            }
            else throw new ArgumentNullException();
        }
        private void Search()
        {
                String url = "";
                try
                {
                    url += "datefrom=" + GetDate(ToDateTime(from.Value)) + "&";
                    url += "dateto=" + GetDate(ToDateTime(to.Value)) + "&";
                }
                catch (ArgumentNullException) { }

                if (typeSelect.SelectedIndex!=0)
                {
                    url += "type=" + data.GetTypeID((String)typeSelect.SelectedItem) + "&";
                }
                if (typeSelect.Visibility == System.Windows.Visibility.Visible 
                    && signerSelect.Visibility == System.Windows.Visibility.Visible
                    && !String.IsNullOrEmpty((String)orgSelect.SelectedItem))
                {
                    url += "org=" + data.getOrgId((String)orgSelect.SelectedItem) + "&";
                    if (!String.IsNullOrEmpty((String)signerSelect.SelectedItem))
                    {
                        url += "signer=" + data.getSignerId((String)signerSelect.SelectedItem) + "&";
                    }
                }
                if (!String.IsNullOrEmpty((String)tagSelect.SelectedItem))
                {
                    url += "tag=" + data.getTagId((String)tagSelect.SelectedItem) + "&";
                }
            
                Go(url);

            }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            from.Value = new DateTime(2010, 10, 1);
            to.Value = DateTime.Today;
        }

        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/About.xaml",UriKind.Relative));
        }

        private void ApplicationBarIconButton_Click_1(object sender, EventArgs e)
        {
            if (panorama.SelectedIndex == 0)
            {
                Search();
            }
            if (panorama.SelectedIndex == 1)
            {
                NavigationService.Navigate(new Uri("/DataViz.xaml?filter=" + (vto.Value.Value.Subtract(vfrom.Value.Value) > TimeSpan.FromDays(7)).ToString() + "&sort=" + (rsign.IsChecked.Value ? "signer" : "org") + "&to=" + GetDate(vto.Value.Value) + "&from=" + GetDate(vfrom.Value.Value), UriKind.Relative));
            }
        }


        private void rorg_Checked(object sender, RoutedEventArgs e)
        {
            if (sender == rorg)
            {
                rsign.IsChecked = false;
            }
            else
            {
                rorg.IsChecked = false;
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            vto.Value = DateTime.Now;
            vfrom.Value = DateTime.Now.Subtract(TimeSpan.FromDays(1));
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            vto.Value = DateTime.Now;
            vfrom.Value = DateTime.Now.Subtract(TimeSpan.FromDays(365));
        }

    }
}